package com.wlm.service.impl;

import com.wlm.dao.ItemDescMapper;
import com.wlm.dao.ItemMapper;
import com.wlm.pojo.Item;
import com.wlm.pojo.ItemDesc;
import com.wlm.service.ItemService;
import com.wlm.vo.EasyUITable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class ItemServiceImpl implements ItemService {

    @Resource
    private ItemMapper itemMapper;

    @Resource
    private ItemDescMapper itemDescMapper;

    @Override
    public EasyUITable findItemByPage(Integer page, Integer rows) {
        int total = itemMapper.selectCount(null);

        int start = (page - 1) * rows;

        List<Item> itemList = itemMapper.findItemByPage(start, rows);

        return new EasyUITable(total, itemList);
    }

    @Override
    @Transactional // 控制事物
    public void saveItem(Item item, ItemDesc itemDesc) {
        item.setStatus(1).setCreated(new Date()).setUpdated(item.getCreated());

        // insert()方法会将自增主键的值设置到item对象中
        itemMapper.insert(item);

        // 新增商品描述
        itemDesc.setItemId(item.getId()).setCreated(item.getCreated()).setUpdated(item.getCreated());

        itemDescMapper.insert(itemDesc);
    }

    @Override
    public void updateItem(Item item) {
        item.setUpdated(new Date());
        itemMapper.updateById(item);
    }

    @Override
    public void deleteItems(Long[] ids) {
        List<Long> idList = Arrays.asList(ids);
        itemMapper.deleteBatchIds(idList);
    }

    @Override
    public void updateItemState(int status, Long[] ids) {
        for(Long id : ids) {
            Item item = new Item();
            item.setId(id).setStatus(status).setUpdated(new Date());
            itemMapper.updateById(item);
        }
    }

    @Override
    public ItemDesc findItemDescById(Long itemId) {
        return itemDescMapper.selectById(itemId);
    }

}
